package com.power.structure.linked;

/**
 * @description:
 * @author: jiangnan
 * @time: 2021/6/11 2:43 下午
 */
public class DoubleLinkedList {
    private Node head;
    private Node tail;
    int size;

    class Node {
        Node pre;
        Node next;
        int value;

        public Node() {
        }

        public Node(Node pre, Node next, int value) {
            this.pre = pre;
            this.next = next;
            this.value = value;
        }

        public Node(int value) {
            this.value = value;
        }
    }

    public void add(int value) {
        Node node = new Node(value);
        //如果为空链表
        if (size == 0) {
            tail = head = node;
        } else if (size == 1) {
            tail = node;
            head.next = tail;
            tail.pre = head;
        } else {
            tail.next = node;
            node.pre = tail;
            tail = node;
        }
        size++;
    }


    public void remove(int element) {
        Node tmp = head;

        while (tmp != null) {
            if (tmp.value == element) {
                tmp.pre.next = tmp.next;
                tmp.next.pre = tmp.pre;
                size--;
            }
            tmp = tmp.next;
        }
    }

    public Node firstNode() {
        return head;
    }

    public Node lastNode() {
        return tail;
    }

    public void display(Node head) {
        Node tmp = head;
        while (tmp != null) {
            System.out.print("  " + tmp.value);
            tmp = tmp.next;
        }
        System.out.println("\n");
    }

    public void replace(int oldElement, int newElement) {
        Node tmp = head;
        while (tmp != null) {
            if (tmp.value == oldElement) {
                tmp.value = newElement;
            }
            tmp = tmp.next;
        }
    }

    public static void main(String[] args) {
        DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
        for (int i = 0; i < 10; i++) {
            doubleLinkedList.add(i);
        }

        doubleLinkedList.display(doubleLinkedList.head);
        System.out.println("firstNode:: " + doubleLinkedList.firstNode().value);
        System.out.println("lastNode:: " + doubleLinkedList.lastNode().value);
        doubleLinkedList.replace(2, 100);
        doubleLinkedList.display(doubleLinkedList.head);

        doubleLinkedList.remove(4);
        doubleLinkedList.display(doubleLinkedList.head);
        System.out.println(doubleLinkedList.size);
    }
}
